package com.example.demo.service.impl;

import com.example.demo.mapper.TestRecordMapper;
import com.example.demo.model.TestRecord;
import com.example.demo.service.MbtiCalculationService;
import com.example.demo.service.TestRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class TestRecordServiceImpl implements TestRecordService {
    
    @Autowired
    private TestRecordMapper testRecordMapper;
    
    @Autowired
    private MbtiCalculationService mbtiCalculationService;

    @Override
    public TestRecord findById(Integer recordId) {
        return testRecordMapper.findById(recordId);
    }

    @Override
    public List<TestRecord> findByUserId(Integer userId) {
        return testRecordMapper.findByUserId(userId);
    }

    @Override
    @Transactional
    public TestRecord create(TestRecord testRecord) {
        // 设置默认值
        if (testRecord.getUserId() == null) {
            testRecord.setUserId(1);
        }
        if (testRecord.getTestDate() == null) {
            testRecord.setTestDate(new Date());
        }
        testRecordMapper.insert(testRecord);
        return testRecord;
    }

    @Override
    @Transactional
    public TestRecord update(TestRecord testRecord) {
        testRecordMapper.update(testRecord);
        return testRecord;
    }

    @Override
    @Transactional
    public Boolean deleteById(Integer recordId) {
        return testRecordMapper.deleteById(recordId) > 0;
    }
    
    @Override
    public TestRecord getTestResult(Integer recordId) {
        // 获取基本测试记录信息
        TestRecord testRecord = findById(recordId);
        if (testRecord == null) {
            return null;
        }
        
        // 直接返回已计算好的测试记录
        // 注意：在新的设计中，答题结果直接通过TestRecordController.submitAnswers方法计算并保存
        // 此方法只需返回已有的测试记录即可
        return testRecord;
    }
    
    @Override
    public List<TestRecord> findCompletedRecordsByOrg(Integer orgId, String orgType) {
        return testRecordMapper.findCompletedRecordsByOrg(orgId, orgType);
    }
} 